package com.jhf.youke.autocompleted.app.executor;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.json.JSONUtil;
import com.jhf.youke.autocompleted.domain.converter.AutoCompletedConverter;
import com.jhf.youke.autocompleted.domain.model.Do.AutoCompletedDo;
import com.jhf.youke.autocompleted.domain.model.dto.AutoCompletedDto;
import com.jhf.youke.autocompleted.domain.model.vo.AutoCompletedVo;
import com.jhf.youke.autocompleted.domain.service.AutoCompletedService;
import com.jhf.youke.core.ddd.BaseAppService;
import com.jhf.youke.core.entity.Pagination;
import com.jhf.youke.core.utils.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author RHJ
 */
@Slf4j
@Service
public class AutoCompletedAppService extends BaseAppService {

    @Resource
    private AutoCompletedService autoCompletedService;

    @Resource
    private AutoCompletedConverter autoCompletedConverter;


    public boolean update(AutoCompletedDto dto) {
        AutoCompletedDo autoCompletedDo =  autoCompletedConverter.dto2Do(dto);
        return autoCompletedService.update(autoCompletedDo);
    }

    public boolean delete(AutoCompletedDto dto) {
        AutoCompletedDo autoCompletedDo =  autoCompletedConverter.dto2Do(dto);
        return autoCompletedService.delete(autoCompletedDo);
    }


    public boolean insert(AutoCompletedDto dto) {
        AutoCompletedDo autoCompletedDo =  autoCompletedConverter.dto2Do(dto);
        return autoCompletedService.insert(autoCompletedDo);
    }

    public Optional<AutoCompletedVo> findById(Long id) {
        return autoCompletedService.findById(id);
    }


    public boolean remove(Long id) {
        return autoCompletedService.remove(id);
    }


    public List<AutoCompletedVo> findAllMatching(AutoCompletedDto dto) {
        AutoCompletedDo autoCompletedDo =  autoCompletedConverter.dto2Do(dto);
        return autoCompletedService.findAllMatching(autoCompletedDo);
    }


    public Pagination<AutoCompletedVo> selectPage(AutoCompletedDto dto) {
        AutoCompletedDo autoCompletedDo =  autoCompletedConverter.dto2Do(dto);
        return autoCompletedService.selectPage(autoCompletedDo);
    }



    public List<Map<String,String>> autoCompleted(AutoCompletedDto dto) throws Exception{
        String my = CacheUtils.get(dto.getKey());
        log.info("my {}", my);
        //构建
        DES des =  SecureUtil.des( Base64.getDecoder().decode(my));

        //解密为原字符串
        String sql = des.decryptStr(dto.getSql());
        log.info("解密 {}", sql);
        Map<String,Object> map =  JSONUtil.toBean(sql,Map.class);
        List<Map<String,String>> list = autoCompletedService.autoCompleted(map);

        return list;
    }
}

